package com.xueyi.core.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述 计时器切面
 *
 * @author 俞烨
 * @date 2024-03-18 17
 */
@Component
@Aspect
@Slf4j
public class TimeIntervalAspect {

    @Around("@annotation(com.xueyi.core.annotations.TimeInterval)")
    public Object timeInterval(ProceedingJoinPoint pjp) throws Throwable {

        String enableTimeInterval = System.getProperty("enableTimeInterval");
        TimeInterval timer = DateUtil.timer();
        Object proceed = pjp.proceed();
        if ("1".equals(enableTimeInterval)) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String requestUri = "";
            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();
                requestUri = request.getRequestURI();
            }
            log.info("接口: {} , 方法名: {} , 总耗时: {}", requestUri,
                    ((MethodSignature) pjp.getSignature()).getMethod().getName(),
                    timer.interval());
        }
        return proceed;
    }
}
